/*
 * Copyright (C) 2016 Baidu, Inc. All Rights Reserved.
 */
package me.cuilei.springbootdemo.user;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by cuilei05 on 16/9/27.
 */
@RestController
@Transactional
public class UserController {
    @Autowired
    UserRepository userRepository;

    @Autowired
    AdminConfig adminProperties;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "redisTemplate")
    private ValueOperations<String, User> userValueOperations;

    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    User get(@PathVariable("id") Long id) {
        logger.debug("Start to get user, id:{}", id);
        String userkey = generateUserKey(id);
        User user = userValueOperations.get(generateUserKey(id));
        logger.debug("get from redis, key:{}, value:{}", userkey, user);
        if (user == null) {
            user = userRepository.findByUserId(id);
            logger.debug("get from db, id:{}, value:{}", id, user);
            if (user == null) {
                throw new UserNotFoundException();
            }
            userValueOperations.set(userkey, user, 5, TimeUnit.SECONDS);
        }
        return user;
    }

    @GetMapping("/user/name/{name}")
    List<User> get(@PathVariable("name") String name) {
        final List<User> user = userRepository.searchByUserName(name);
        return user;
    }

    @GetMapping("/admin/")
    User admin() {
        return new User(adminProperties.getUserId(), adminProperties.getUserName());
    }

    private String generateUserKey(Long userId) {
        return "USER_" + userId;
    }
}
